package com.devshephard.nio.chat.client;

import com.alibaba.fastjson.JSON;
import com.devshephard.nio.chat.user.User;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;
import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                        channel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buffer = (ByteBuf) msg;
                                String loginToken = buffer.toString(Charset.defaultCharset());
                                if("登录成功".equals(loginToken)){ //登录成功,则可以发消息
                                    System.out.println("登录成功");
                                    new Thread(()->{
                                        while (true){
                                            Scanner scanner = new Scanner(System.in);
                                            String systemInMsg = scanner.nextLine();
                                            //发送消息
                                            ctx.writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes(systemInMsg.getBytes()));
                                        }
                                    }).start();
                                }else{
                                    System.out.println(buffer.toString(Charset.defaultCharset())); //不是成功就是失败
                                }
                            }
                        });
                    }
                })
                .connect("127.0.0.1",8080);

        channelFuture.sync();
        User user = new User("李四","456");
        String userJson = JSON.toJSONString(user);
        channelFuture.channel().writeAndFlush(userJson);
    }

}
